const { querySql, queryOne } = require("../utils/sql");
const dayjs = require("dayjs");
const path = require("path");
const fs = require("fs");
const { verify } = require("../utils/auth-jwt");
const { setLog } = require("../utils/log.js");

// 根据记录数总数和分页数获到页总数
function pageCount(totalnum, limit) {
  return totalnum > 0
    ? totalnum < limit
      ? 1
      : totalnum % limit
      ? parseInt(totalnum / limit) + 1
      : totalnum / limit
    : 0;
}
// 格式化文件大小
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return "0 Bytes";

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}
// 分页查询方法
async function getDataListByCate(req, res) {
  let { pageSize, pageNum, category, fileName } = req.query;
  // console.log("-------", req);
  // let authorization = req.headers.authorization.split(" ")[1];
  // console.log("-------", req.getToken());
  let { id } = req.getToken();
  // console.log("-------", id);

  const startIndex = (pageNum - 1) * pageSize;
  let queryString = `SELECT * FROM file_info `;
  if (category != "all") {
    queryString += `WHERE category = ${category} and uid = ${id} `;
  } else {
    if (fileName) {
      queryString += `WHERE fileName LIKE '%${fileName}%' and uid = ${id} `;
    } else {
      queryString += `WHERE uid = ${id} `;
    }
  }
  queryString += `LIMIT ${startIndex}, ${pageSize}`;
  // console.log("========queryString=========", queryString);

  let data = await querySql(queryString);
  const countSql = "select count(*) count from file_info";
  let countData = await querySql(countSql);
  let count = countData[0].count;
  //   console.log("data", data);

  let pageData = {
    total: count,
    pages: pageCount(count, pageSize),
    records: data.map((item) => {
      return {
        ...item,
        updateTime: dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
        fileSize: formatBytes(item.fileSize),
      };
    }),
  };

  res.send({
    code: 0,
    data: pageData,
    success: true,
    message: "",
  });
}
//获取文件
async function getFile(req, res) {
  let file_name = req.query.filePath;
  let contentType = req.query.contentType;
  if (!file_name) {
    return res.status(400).json({
      code: -1,
      data: null,
      msg: error.message,
    });
  }
  try {
    let file_path = path.join(__dirname, "../", file_name);
    // 检查文件是否存在
    fs.access(file_path, fs.constants.F_OK, (err) => {
      if (err) {
        // 如果文件不存在，返回404错误
        return res.status(404).send("File not found");
      }
      // 使用createReadStream创建文件读取流
      const readStream = fs.createReadStream(file_path);
      const encodedFileName = `"${encodeURIComponent(file_path).replace(
        /"/g,
        '\\"'
      )}"`; // 对文件名进行编码并处理引号
      // 设置响应头，指定内容类型和可能的其他选项
      res.setHeader(
        "Content-Type",
        contentType ? contentType : `application/octet-stream`
      ); // 对于未知类型的文件，可以使用octet-stream
      res.setHeader(
        "Content-Disposition",
        `attachment; filename="${encodedFileName}"`
      ); // 提示浏览器这是一个下载文件

      // 将文件流连接到响应对象
      readStream.pipe(res);
      // setLog(
      //   req.getToken()?.id,
      //   `用户${
      //     req.getToken()?.username
      //   }下载了文件名为：${encodedFileName}的文件`
      // );
      // 监听错误事件（可选，但推荐）
      readStream.on("error", (err) => {
        console.error("Error reading file:", err);
        res.status(500).send("Error reading file");
      });
    });
  } catch (err) {
    // console.log("==========getFile(err)============");
    // console.log(err);
    res.status(404).json({
      code: -1,
      msg: `未查找到${file_name}`,
    });
  }
}

// 获取日志
const getLog = async (req, res) => {
  // console.log(req);

  let { pageSize, pageNum } = req.query;

  const startIndex = (pageNum - 1) * pageSize;
  let queryString = `SELECT * FROM log `;

  queryString += `LIMIT ${startIndex}, ${pageSize}`;
  // console.log("========queryString=========", queryString);

  let data = await querySql(queryString);
  const countSql = "select count(*) count from log";
  let countData = await querySql(countSql);
  let count = countData[0].count;
  // console.log("data", data);

  let pageData = {
    total: count,
    pages: pageCount(count, pageSize),
    records: data.map((item) => {
      return {
        ...item,
        operationTime: dayjs(item.operationTime).format("YYYY-MM-DD HH:mm:ss"),
      };
    }),
  };

  res.send({
    code: 0,
    data: pageData,
    success: true,
    message: "",
  });
};
// 获取用户列表
const getUser = async (req, res) => {
  // console.log(req);

  let { pageSize, pageNum, id } = req.query;

  const startIndex = (pageNum - 1) * pageSize;
  let queryString = `SELECT * FROM users `;
  if (id) {
    queryString += `WHERE id = ${id} `;
  }

  queryString += `LIMIT ${startIndex}, ${pageSize}`;
  // console.log("========queryString=========", queryString);

  let data = await querySql(queryString);
  const countSql = "select count(*) count from users";
  let countData = await querySql(countSql);
  let count = countData[0].count;
  // console.log("data", data);

  let pageData = {
    total: count,
    pages: pageCount(count, pageSize),
    records: data.map((item) => {
      return {
        ...item,
        createtime: dayjs(item.operationTime).format("YYYY-MM-DD HH:mm:ss"),
      };
    }),
  };

  res.send({
    code: 0,
    data: pageData,
    success: true,
    message: "",
  });
};

module.exports = {
  getDataListByCate,
  getFile,
  getLog,
  getUser,
};
